package com.fly.interceptor;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fly.bean.Users;
import com.fly.service.PermissionService;
import com.fly.util.JWTUtil;
import com.fly.util.Msg;
import org.springframework.stereotype.Service;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;


@Service
public class LoginInterceptor implements HandlerInterceptor {

    @Resource
    private PermissionService permissionService;

    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {
        //得到token
        String token = httpServletRequest.getHeader("Authorization");
        System.out.println("asddddddd" + token);
        //解密token
        Users user = JWTUtil.unsign(token, Users.class);
        if (user != null){
            System.out.println(user.getUserName());
        }
        //设置编码格式
        httpServletResponse.setCharacterEncoding("UTF-8");
        //如果用户为空表示没有登录没有用户信息，返回false，跳至登录界面
        if (user == null) {
            //写出
            PrintWriter printWriter = httpServletResponse.getWriter();
            //相应类型
            httpServletResponse.setContentType("application/json; charset=utf-8");
            ObjectMapper mapper = new ObjectMapper();
            //转换为字符串
            String jsonString = mapper.writeValueAsString(Msg.noLogin());
            //写出json数据
            printWriter.print(jsonString);
            printWriter.flush();
            printWriter.close();

            return false;
        } else {
            //用户已登录
            //请求地址（返回除去host（域名或者ip）部分的路径）
            String uri = httpServletRequest.getRequestURI();
            //资源路径名
            String propertiesUri = uri.substring(uri.lastIndexOf("/") + 1);

            //得到用户ID信息
            Integer userId = user.getUserId();
            //通过用户Id得到角色Id信息
            Integer roleId = permissionService.selectRoleIdByUserId(userId);

            //通过角色Id得到资源URI信息
            String[] resources = permissionService.selectRoleRequestURI(roleId);
            //如果资源名存在则返回true，表示有权限
            for (String resource : resources) {
                if (propertiesUri.equals(resource)) {
                    return true;
                }
            }
            //写出
            PrintWriter printWriter = httpServletResponse.getWriter();
            //相应类型
            httpServletResponse.setContentType("application/json; charset=utf-8");
            ObjectMapper mapper = new ObjectMapper();
            //以字符串的形式
            String jsonString = mapper.writeValueAsString(Msg.noPermission());
            printWriter.print(jsonString);
            printWriter.flush();
            printWriter.close();

            return false;
        }

    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

    }
}
